/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package strugglechess;

import java.io.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.midi.*;

/**
 *
 * @author olivier
 */
/**
 * Plays a midi file provided
 **/
public class MidiPlayer {

    private Sequencer sequencer;
    private int trackIndex;
    private boolean randomPlay;
    private ArrayList<String> playlist;

    // implement the constructor with
    MidiPlayer() {
        playlist = new ArrayList<String>();
        trackIndex = 0;
        randomPlay = false;
    }

    void setRandom(boolean isActivated) {
        randomPlay = isActivated;
    }

    /**
     * Load the midi files present in the given folder to the playlist
     * @param path location of the midi files to load
     */
    void loadPlaylist(String path) {
        // TODO implement this method

        File folder = new File(path);
        File[] listOfFiles = folder.listFiles();
        String filename = "";

        System.out.println("Loading the playlist:");
        for (int i = 0; i < listOfFiles.length; i++) {
            filename = listOfFiles[i].getName();
            if (filename.endsWith(".mid")) {
                playlist.add(path + filename);
                System.out.println("+ " + filename);
            }
        }

    }

    /**
     * Play the list of midi files
     * 
     */
    void play() {

        //int i = 0;
        File midiFile = new File(playlist.get(trackIndex));
        try {
            sequencer = MidiSystem.getSequencer();
            sequencer.setSequence(MidiSystem.getSequence(midiFile));
            sequencer.open();
            sequencer.start();

            // TODO add a thread to check if the track is over and do next (freq=5000msec)
            /*
            while(true) {
            if(sequencer.isRunning()) {
            try {
            Thread.sleep(1000); // Check every second
            } catch(InterruptedException ignore) {
            break;
            }
            } else {
            break;
            }
            }
             */

        } catch (MidiUnavailableException mue) {
            System.out.println("ERROR: Midi device unavailable");
        } catch (InvalidMidiDataException imde) {
            System.out.println("ERROR: Invalid Midi data");
        } catch (IOException ioe) {
            System.out.println("ERROR: I/O exception");
        }
    }

    /**
     * Stop the play of the playlist
     */
    void stop() {

        sequencer.stop();
        sequencer.close();
    }

    /**
     * Jump to the next track
     */
    void next() {
        if (randomPlay && playlist.size() > 1) {
            int newTrack = trackIndex;
            while (newTrack == trackIndex) {
                newTrack = (int) (Math.random() * ((double) playlist.size()));
            }
            trackIndex = newTrack;
        } else {
            trackIndex = (trackIndex + 1) % (playlist.size());
        }

        // if playing, relaunch the playlist at the correct track

        if (sequencer.isRunning()) {
            stop();
            play();
        }

    }

    /**
     * Go back to the previous track
     */
    void previous() {
        if (randomPlay) {
            System.out.println("Previous track is not accessible in random mode");

        } else {
            trackIndex = (trackIndex - 1) % (playlist.size());
        }

        // if playing, relaunch the playlist at the correct track

        if (sequencer.isRunning()) {
            stop();
            play();
        }

    }
}

